package chapter25;

/**
 * 所有节点对的最短路径-最短路径
 */
public class AllPairs {

    public static void printAlPairsShortestPath(int[][] pai, int i, int j) {
        if (i == j) {
            System.out.println(i);
        } else if (pai[i][j] == -1) {
            System.out.println("no path from i to j exists");
        } else {
            printAlPairsShortestPath(pai, i, pai[i][j]);
            System.out.println(j);
        }
    }

    public static int[][] extendShortestPath(int[][] L, int[][] W) {
        int n = L.length;
        int[][] L1 = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                L1[i][j] = Integer.MAX_VALUE;
                for (int k = 0; k < n; k++) {
                    int a = L[i][k];
                    int b = W[k][j];
                    int c;
                    if (a != Integer.MAX_VALUE && b != Integer.MAX_VALUE) {
                        c = a + b;
                    } else {
                        c = Integer.MAX_VALUE;
                    }
                    L1[i][j] = Math.min(L1[i][j], c);
                }
            }
        }
        return L1;
    }

    public static int[][] slowAllPairsShortestPaths(int[][] W) {
        int n = W.length;
        int[][][] L = new int[n][n][n];
        L[0] = W;
        for (int m = 1; m < n; m++) {
            L[m] = extendShortestPath(L[m - 1], W);
        }
        return L[n - 1];
    }

    public static int[][] fasterAllPairsShortestPaths(int[][] W) {
        int n = W.length;
        int[][] L = W;
        int m = 1;
        while (m < n - 1) {
            L = extendShortestPath(L, L);
            m *= 2;
        }
        return L;
    }

}
